package com.young.financial.service.impl;

import com.young.financial.config.UrlConstants;
import com.young.financial.constants.FinancialPayConfigEnumConstants;
import com.young.financial.service.FinancialBalancePayService;
import com.young.financial.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * describe:
 *
 * @author zhaopengjun
 * @date 2019/9/2 8:27
 */
@Service
public class FinancialBalancePayServiceImpl implements FinancialBalancePayService {
    @Value("${balancePlatform.platfromMarking}")
    private String platfromMarking;
    @Autowired
    private HttpClientUtils httpClientUtils;
    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private RedisUtils redisUtils;
    public static final Logger logger = LoggerFactory.getLogger(FinancialBalancePayServiceImpl.class);
    @Override
    public Map<String,Object> balancePay(Map<String, Object> requestMap) {
        logger.info("优店余额预支付请求金融中心"+JsonUtils.objectToJson(requestMap));
        //订单号
        String orderNum = requestMap.get("orderNum").toString();
        //异步回执地址
        //String notifyUrl = requestMap.get("notifyUrl").toString();
        //会员id
        String customerUuid = requestMap.get("customerUuid").toString();
        //余额支付总金额
        String payMoney = requestMap.get("payMoney").toString();
        //交易描述
        String subject = requestMap.get("subject").toString();

        //获取支付通道类型id
        if(StringUtils.isEmpty(customerUuid)
                ||StringUtils.isEmpty(payMoney)||StringUtils.isEmpty(orderNum)
                ||StringUtils.isEmpty(subject)||StringUtils.isEmpty(customerUuid)){
            return ApiResult.paramIsNull();
        }

        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }

        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("platfromMarking",platfromMarking);
        requestMap.put("payType", FinancialPayConfigEnumConstants.ENUM_PAYTYPE_YS_WECHATPAY);
        String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.WECHAT_BALANCEPAY_URL,requestMap);
            Map<String, Object> map = JsonUtils.jsonToMap(result);
            logger.info("优店余额预支付信息回执内容:{}",JsonUtils.objectToJson(map));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialBalancePayServiceImpl----请求金融中心余额支付接口失败 地址:{},错误信息:{}",UrlConstants.WECHAT_BALANCEPAY_URL,e.getMessage());
        }
        return null;
    }

    @Override
    public Map<String, Object> balanceRefund(Map<String, Object> requestMap) {
        logger.info("接受优店退款参数"+JsonUtils.objectToJson(requestMap));
        //参数校验
        //用户id
        String customerUuid = requestMap.get("customerUuid").toString();
        //退款金额
        String payMoney = requestMap.get("payMoney").toString();
        //退款单号
        String prePayNo = requestMap.get("prePayNo").toString();
        //退款原因
        String refundReason = requestMap.get("refundReason").toString();
        if(StringUtils.isEmpty(customerUuid)||StringUtils.isEmpty(payMoney)
                ||StringUtils.isEmpty(prePayNo)||StringUtils.isEmpty(refundReason)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        Map<String, Object> reqmap = new HashMap<>();
        reqmap.put("customerUuid",customerUuid);
        reqmap.put("payMoney",new BigDecimal(payMoney));
        reqmap.put("prePayNo",prePayNo);
        reqmap.put("tgAccessToken",accessToken);
        reqmap.put("platfromMarking",platfromMarking);
        reqmap.put("payType",FinancialPayConfigEnumConstants.ENUM_PAYTYPE_YS_WECHATPAY);
        //todo 保存请求参数
        String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.WECHAT_BALANCEREFUND_URL,reqmap);
            Map<String, Object> map = JsonUtils.jsonToMap(result);
            logger.info("FinancialBalancePayServiceImpl----请求金融中心余额退款接口成功 地址:{},余额退款请求参数:{}",UrlConstants.WECHAT_BALANCEREFUND_URL,map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialBalancePayServiceImpl----请求金融中心余额退款接口失败 地址:{},错误信息:{}",UrlConstants.WECHAT_BALANCEREFUND_URL,e.getMessage());
        }
        return ApiResult.failure();
    }

    @Override
    public Boolean balancePayment(Map<String, Object> requestMap) {
        logger.info("优点余额代付请求金融中心代付参数:{}",JsonUtils.objectToJson(requestMap));
        Boolean agentcyStatus = false;
        //参数校验
        String outTradeNo = requestMap.get("outTradeNo").toString();
        String balancePaymentAmount = requestMap.get("balancePaymentAmount").toString();
        String bankName = requestMap.get("bankName").toString();
        String subject = requestMap.get("subject").toString();
        String bankCity = requestMap.get("bankCity").toString();
        String bankAccountName = requestMap.get("bankAccountName").toString();
        String bankCardType = requestMap.get("bankCardType").toString();
        String bankAccountType = requestMap.get("bankAccountType").toString();
        String bankAccountNo = requestMap.get("bankAccountNo").toString();
        if (StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(balancePaymentAmount)
                ||StringUtils.isEmpty(bankName)
                ||StringUtils.isEmpty(subject)||StringUtils.isEmpty(bankAccountNo)
                ||StringUtils.isEmpty(bankCity)||StringUtils.isEmpty(bankAccountName)
                ||StringUtils.isEmpty(bankCardType)||StringUtils.isEmpty(bankAccountType)){
            return false;
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("payType", FinancialPayConfigEnumConstants.ENUM_PAYTYPE_YS_WECHATPAY);
        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("platfromMarking",platfromMarking);
            String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.WECHAT_BALANCEAGENCY_URL,requestMap);
            logger.info("FinancialBalancePayServiceImpl----请求金融中心余额代付接口成功 地址:{},余额代付请求回执:{}",UrlConstants.WECHAT_BALANCEAGENCY_URL,result);
            Map<String, Object> resultMap = JsonUtils.jsonToMap(result);
            agentcyStatus = (Boolean) resultMap.get("agentcyStatus");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialBalancePayServiceImpl----请求金融中心余额代付接口失败 地址:{},错误信息:{}",UrlConstants.WECHAT_BALANCEAGENCY_URL,e.getMessage());
        }
        logger.info("回执优店余额代付结果"+agentcyStatus);
        return agentcyStatus;
    }

    @Override
    public Map<String, Object> balancePayQuery(String requestStr) {
        String result = "";
        if(StringUtils.isEmpty(requestStr)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("tgAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("tgAccessToken",accessToken);
        paraMap.put("orderNum",requestStr);
        try {
            result= httpClientUtils.doPost(UrlConstants.WECHAT_BALANCEPAYQUERY_URL,paraMap);
            logger.info("FinancialBalancePayServiceImpl----请求金融中心余额主动查询接口成功 地址:{},主动查询请求参数:{}",UrlConstants.WECHAT_BALANCEPAYQUERY_URL,result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialBalancePayServiceImpl----请求金融中心余额主动查询接口失败 地址:{},错误信息:{}",UrlConstants.WECHAT_BALANCEPAYQUERY_URL,e.getMessage());
        }
        return JsonUtils.jsonToMap(result);
    }

    @Override
    public Map<String, Object> balancePaymentQuery(Map<String, Object> requestMap) {
        logger.info("优店金融调用金融中心余额代付查询参数 :{}",JsonUtils.objectToJson(requestMap));
        String result = "";
        Object temp = null;
        temp = requestMap.get("out_trade_no");
        String outTradeNo = temp != null ?temp.toString():null;
        temp = requestMap.get("shopdate");
        String shopdate = temp != null ?temp.toString():null;

        if (StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(shopdate)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("tgAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("payType", FinancialPayConfigEnumConstants.ENUM_PAYTYPE_YS_WECHATPAY);
        requestMap.put("platfromMarking",platfromMarking);
        try {
            result= httpClientUtils.doPost(UrlConstants.BALANCE_PAYMENT_QUERY_URL,requestMap);
            logger.info("FinancialBalancePayServiceImpl----请求金融中心余额代付主动查询接口成功 地址:{},余额代付主动查询请求参数:{}",UrlConstants.BALANCE_PAYMENT_QUERY_URL,result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialBalancePayServiceImpl----请求金融中心余额代付主动查询接口失败 地址:{},错误信息:{}",UrlConstants.BALANCE_PAYMENT_QUERY_URL,e.getMessage());
        }
        logger.info("FinancialBalancePayServiceImpl----请求金融中心余额代付主动查询接口成功 地址:{},余额代付主动查询请求参数:{}",UrlConstants.BALANCE_PAYMENT_QUERY_URL,JsonUtils.jsonToMap(result));
        return JsonUtils.jsonToMap(result);
    }
}
